package com.choosefine.springboot.devops.bargain.controller;


import com.choosefine.springboot.devops.activity.model.Activity;
import com.choosefine.springboot.devops.bargain.dto.UpdateBargainDTO;
import com.choosefine.springboot.devops.bargain.model.Bargain;
import com.choosefine.springboot.devops.bargain.service.BargainService;
import com.choosefine.springboot.devops.bargain.dto.InsertBargainDTO;
import com.choosefine.springboot.devops.base.config.BargainUtil;
import com.choosefine.springboot.devops.base.config.MapUtil;
import com.choosefine.springboot.devops.base.result.ReturnMSG;
import com.choosefine.springboot.devops.base.serviceImpl.RedisServiceImpl;
import com.choosefine.springboot.devops.base.weixin.Event;
import com.choosefine.springboot.devops.participate.model.Participate;
import com.choosefine.springboot.devops.participate.model.RedisParticipate;
import com.choosefine.springboot.devops.user.model.User;
import com.choosefine.springboot.devops.user.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/bargain")
public class BargainController {
    @Autowired
    private BargainService bargainService;
    @Autowired
    private UserService userService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private Event event;
    @Autowired
    private RedisServiceImpl redisService;

    @GetMapping("/{id}")
    public String selectById(@PathVariable("id") Integer id) throws JsonProcessingException {
        Bargain result = bargainService.selectById(id);
        return objectMapper.writeValueAsString(result);
    }

    @PostMapping
    public String insert(@Valid InsertBargainDTO insertBargainDTO, BindingResult result, HttpServletResponse response) throws IOException {
        ReturnMSG returnMSG = new ReturnMSG();
        if (result.hasErrors()) {
            return objectMapper.writeValueAsString(returnMSG.paramError());
        } else {
            if (insertBargainDTO.getWxCode() == null) {
                event.event("participate/" + insertBargainDTO.getParticipateId(), response,insertBargainDTO.getActivityId());
                return null;
            } else {
                User user = userService.selectByCode(insertBargainDTO.getWxCode());
                if (user == null || user.getStatus() != 1) {
                    event.event("participate/" + insertBargainDTO.getParticipateId(), response,insertBargainDTO.getActivityId());
                    return null;
                }
                String redisParticipate=redisService.get("Participate"+insertBargainDTO.getParticipateId());
                String redisActivity=redisService.get("Activity"+insertBargainDTO.getActivityId());
                String bargainHistory=redisService.get("Bargain"+insertBargainDTO.getParticipateId());
                String [] bargainArray=null;
                if(bargainHistory!=null){bargainArray=bargainHistory.split(",");}
                if(redisActivity==null){
                    return objectMapper.writeValueAsString(returnMSG.error("未找到此活动！"));
                }
                if(redisParticipate==null){
                    return objectMapper.writeValueAsString(returnMSG.error("未参加活动！"));
                }
                if(bargainArray!=null){
                    for(String now:bargainArray){
                        if(now.equals(insertBargainDTO.getWxCode())){
                            return objectMapper.writeValueAsString(returnMSG.error("已经砍过了！"));
                        }
                    }
                }

                if(redisParticipate==null||redisActivity==null){
                    return objectMapper.writeValueAsString(returnMSG.paramError());
                }else{
                    RedisParticipate participate1=objectMapper.readValue(redisParticipate,RedisParticipate.class);
                    if(participate1.getPrice()<=participate1.getButtonPrice()){
                        return objectMapper.writeValueAsString(returnMSG.error("砍价失败，已经砍到底了"));
                    }
                    if(participate1.getNumber()==0){
                        return objectMapper.writeValueAsString(returnMSG.error("砍价失败，砍价次数打到上限"));
                    }

                    double kan=BargainUtil.bargain(participate1);//砍价数量
                    participate1.setPrice(participate1.getPrice()-kan);//砍价成功减价
                    participate1.setBargainNumber(participate1.getBargainNumber()-1);//砍成功后减次数
                    redisService.set("Participate"+insertBargainDTO.getParticipateId(),objectMapper.writeValueAsString(participate1));
                    redisService.set("Bargain"+insertBargainDTO.getParticipateId(),insertBargainDTO.getWxCode()+",");
                    Bargain bargain = new Bargain();
                    BeanUtils.copyProperties(insertBargainDTO, bargain);
                    bargain.setUserId(user.getId());
                    bargain.setPrice(kan);

                    bargainService.save(Bargain.class, MapUtil.transBean2Map(bargain));
                }
                return objectMapper.writeValueAsString(returnMSG.success());
            }
        }
    }

    @PutMapping
    public String update(@Valid UpdateBargainDTO updateBargainDTO, BindingResult result) throws JsonProcessingException {
        ReturnMSG returnMSG = new ReturnMSG();
        if (result.hasErrors()) {
            return objectMapper.writeValueAsString(returnMSG.paramError());
        } else {
            if (bargainService.update(Bargain.class, MapUtil.transBean2Map(updateBargainDTO)) > 0) {
                return objectMapper.writeValueAsString(returnMSG.success());
            } else {
                return objectMapper.writeValueAsString(returnMSG.error());
            }
        }
    }

    @DeleteMapping
    public String delete(Integer id) throws JsonProcessingException {
        ReturnMSG returnMSG = new ReturnMSG();
        if (id == null) {
            return objectMapper.writeValueAsString(returnMSG.paramError());
        } else {
            Map param = new HashMap();
            param.put("id", id);
            if (bargainService.falseDelete(Bargain.class, param) > 0) {
                return objectMapper.writeValueAsString(returnMSG.success());
            } else {
                return objectMapper.writeValueAsString(returnMSG.error());
            }
        }

    }
}
